package org.secangkirkopipanas.gxtcore.server;

import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.io.ClassPathResource;

/**
 * Global application context
 * 
 */
public class ApplicationContext {
	/**
	 * The configuration file
	 */
	private static final String CONTEXT_FILE = "org/secangkirkopipanas/gxtcore/resources/applicationContext.xml";

	/**
	 * Unique instance of the singleton
	 */
	private static ApplicationContext _instance;

	/**
	 * Spring context
	 */
	protected GenericApplicationContext _springContext;

	/**
	 * @return the unique of the instance
	 */
	public static synchronized final ApplicationContext getInstance() {
		if (_instance == null) {
			_instance = new ApplicationContext();
		}
		return _instance;
	}

	/**
	 * Constructor
	 */
	protected ApplicationContext() {
		initContextFile();
	}

	/**
	 * Get a bean from its name
	 */
	public Object getBean(String beanName) {
		return _springContext.getBean(beanName);
	}

	/**
	 * Init Spring context
	 */
	private void initContextFile() {
		_springContext = new GenericApplicationContext();
		XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(
				_springContext);
		xmlReader.loadBeanDefinitions(new ClassPathResource(getContextFile()));
		_springContext.refresh();
	}

	/**
	 * @return the appropriate context file associated with the current
	 *         application configuration
	 */
	private String getContextFile() {
		return CONTEXT_FILE;
	}
}
